package com.cnfangmao.masterdata.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cnfangmao.masterdata.common.response.ResCodeEnum;
import com.cnfangmao.masterdata.common.response.ResBody;
import com.cnfangmao.masterdata.common.utils.MD5Utils;
import com.cnfangmao.masterdata.service.UserService;


@Api(description = "AuthController登录相关", tags = "Auth")
@RestController
@RequestMapping(path = "/auth")
public class AuthController {
	@Autowired
	private UserService userService;
	
	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);


	 /**
     * 登录
     */
    @ApiOperation(value="登录", notes = "登录")
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public ResBody login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
		ResBody resBody = new ResBody();
	     String msg="";
        if(userName==null || userName.isEmpty())
        {
        	resBody.code(ResCodeEnum.PARAM_NULL.getCode());
        	resBody.message("用户名为空");
            return resBody;
        }
        String md5Password =MD5Utils.getMD516(password);
        // 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();
        // 2、将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, md5Password);

        // 3、认证
        try {
            currentUser.login(token);// 传到MyAuthorizingRealm类中的方法进行认证
            Session session = currentUser.getSession();
            session.setAttribute("userName", userName);
            resBody.code(ResCodeEnum.SUCCESS.getCode());
            resBody.message("登录成功");
            resBody.data(true);
            return resBody;
        }catch (UnknownAccountException e)
        {
        	resBody.code(ResCodeEnum.ACCOUNT_NO_EXISTIS.getCode());
            msg = "账号不存在：";
        }
        catch (IncorrectCredentialsException e)
        {
        	resBody.code(ResCodeEnum.AUTH_FAIL.getCode());
            msg = "密码不正确：";
        }
        catch (AuthenticationException e) {
        	resBody.code(ResCodeEnum.FAIL.getCode());
            msg="用户验证失败";
        }
        
        resBody.message(msg);
        return resBody;
	}
	
	 /**
     * 退出登录
     */
    @ApiOperation(value="退出登录", notes = "退出登录")
	@RequestMapping(value="/logout.do",method=RequestMethod.POST)
	public ResBody logout(HttpSession session)
	{
		ResBody resBody = new ResBody();
		    try {
		    	 Subject subject = SecurityUtils.getSubject();
		         subject.logout();
		         resBody.code(ResCodeEnum.SUCCESS.getCode());
		         resBody.message("退出成功");
			} catch (Exception ex) {
				logger.error("LoginController logout err, ",ex);
				   resBody.code(ResCodeEnum.FAIL.getCode());
			       resBody.message("退出失败");
			}

		    return resBody;
	}
}
